//
//  MyCollectsProductViewController.swift
//  weile
//
//  Created by LKM on 16/10/26.
//  Copyright © 2016年 LKM. All rights reserved.
//

import UIKit

class MyCollectsProductViewController:  BaseViewController ,UITableViewDelegate,UITableViewDataSource  {
    
    @IBOutlet weak var tableview: UITableView!
    var mListFooterLoadView :ListFooterLoadView!
    
    var refreshControl: UIRefreshControl!

    override func viewDidLoad() {
        super.viewDidLoad()

        mListFooterLoadView = ListFooterLoadView.createView();
        self.tableview.tableFooterView=mListFooterLoadView;
        
        self.tableview.register(UINib(nibName:"MyCollectsItem", bundle: nil), forCellReuseIdentifier: "cellId")
        
        //tableview参数设置
        tableview.rowHeight = 120.7//10+100+10+0.7
        tableview.separatorStyle = .none
        tableview.contentInset = UIEdgeInsetsMake(0, 0, MainTabBarHeight, 0)
        tableview.scrollIndicatorInsets = tableview.contentInset
        tableview.delegate=self;
        tableview.dataSource = self;
        //tableview参数设置  end
        
        
        // 添加刷新控件
        refreshControl = UIRefreshControl()
        //        refreshControl.attributedTitle = NSAttributedString(string: "松开后自动刷新")
        tableview.addSubview(refreshControl)
        refreshControl.addTarget(self, action: #selector(loadData(_:)), for: .valueChanged)
        // 添加刷新控件 end

        loadData(false)
        
    }
    var listData: [MyCollectsItemTo] = Array();//
    var curPage = 1;//第一开始
    var isLoadIng = false;//是否加载中
    var isLoadAppending = false;//是否加载更多数据
    var hasMoreData=true;//是否有更多数据
    
    @discardableResult
    func loadData(_ isLoadAppend :Bool) -> Bool{
        if isLoadIng {
            return isLoadAppend == isLoadAppending;
        }
        self.isLoadAppending=isLoadAppend;
        isLoadIng=true
        
        if(isLoadAppend){
            mListFooterLoadView.setAppending()
        }else{
            ViewHelp.showProgressActivityDelay(containView: self.view)
            mListFooterLoadView.setRefreing()
        }
        
        let taskSerialNumber=Api.MyCollectProduct(preTaskSerialNumber: nil,page: isLoadAppend ? (curPage + 1) : 1){ (re:ResponEntity) in
            self.isLoadIng=false;
            self.refreshControl.endRefreshing()
            ViewHelp.hideProgressActivity(containView: self.view)
            guard re.isSuccess() else{
                ViewHelp.showTipsView(containView: self.view, tips: re.msg)//成功不显示
                return;
            }
            
            let curData = re.getData() as? [MyCollectsItemTo] ?? [MyCollectsItemTo]();
            
            //数据是那些----
            let hasListData = !(CollectionHelp.isEmpty( curData )) //这次加载的有数据？//!(self.data?.prolist == nil);
            if(self.isLoadAppending){
                self.curPage += hasListData ? 1 : 0;
            }else{
                self.listData.removeAll();
                self.curPage = 1;
            }
            self.listData += curData
            
            self.hasMoreData = hasListData//这次加载是否有数据  觉得了是否有更多数据
            if(self.hasMoreData){//这个是针对这个搜索，后台没做分页的情况
                //打于等于20就是有下一页
                self.hasMoreData = CollectionHelp.size(curData) >= LKMAPIListPageSize;
            }
            //没有更多数据了
            self.mListFooterLoadView.setNone(hasNextPage: hasListData)
            //数据是那些----end
            
            if CollectionHelp.isEmpty(self.listData){
                self.mListFooterLoadView.setNone(tips: "- 您还没收藏任何东西呢 -")
            }
            
            self.tableview.reloadData()
            
            
        }
        curLoadTaskSerialNumber=taskSerialNumber;
        taskAlls.append(taskSerialNumber);
        
        return true;
    }
    func forceRefresh(){
        isLoadIng=false;
        if let ts = curLoadTaskSerialNumber{
            Api.destroyTask(taskSerialNumbers: [ts])
        }
        
        loadData(false);
    }
    
    var curLoadTaskSerialNumber:Int?;
    var taskAlls = [Int]();
    deinit {
        //界面退出肯定就不登陆咯
        Api.destroyTask(taskSerialNumbers: taskAlls);
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: - UITableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.listData.count
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let homeCell = tableView.dequeueReusableCell(withIdentifier: "cellId") as! MyCollectsItem
        homeCell.selectionStyle = .none
        homeCell.mMyCollectsItemTo = self.listData[(indexPath as NSIndexPath).row]
        
        let count:Int=self.tableView( tableView, numberOfRowsInSection:1);
        if(indexPath.row+1>=count){
            //加载更多数据
            if hasMoreData{
                //一般到显示倒数第二个就会去加载
                loadData(true);
            }
            
        }
        
        
        return homeCell
    }
    // MARK: - UITableViewDelegate
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let mMyCollectsItemTo = self.listData[(indexPath as NSIndexPath).row]
        if(mMyCollectsItemTo.kindId == 2){
            ActivityRequest.goProductDetailController(navigationController!,mMyCollectsItemTo.conid!);
        }else{
            ActivityRequest.goArticleDetailController(navigationController!, mMyCollectsItemTo.conid!)
        }
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

import Foundation
import SwiftyJSON

//lkm
class MyCollectsItemTo: NSObject {
    
    var title: String?;//"轻钢别墅"
    var img: String?;//"/UpLoadFiles/20161010/2016101020382211.jpg"
    var channel: Int?;//"0"
    var conid: String?;//"116"
    var id: String?;//"15"
    var islock: Int?;//"0"
    var kindId: Int?;//"2"
    var remark: String?;//""
    var status: Int?;//"0"
    var time_add: String?;//"2016/10/26 11:21:27"
    var type: Int?;//"0"
    var userid: Int?;//"4020"
    
    //dict["data"].dictionaryObject  dict是JSON
    init?(jsons: [String: JSON]?) {
        super.init()
        
        if(jsons == nil){
            return nil
        }
        
        if let dict = jsons{
        self.title = dict["title"]?.string;//"轻钢别墅"
        self.img = dict["img"]?.string;//"/UpLoadFiles/20161010/2016101020382211.jpg"
        self.channel = dict["channel"]?.int;//"0"
        self.conid = dict["conid"]?.string;//"116"
        self.id = dict["id"]?.string;//"15"
        self.islock = dict["islock"]?.int;//"0"
        self.kindId = dict["kindId"]?.int;//"2"
        self.remark = dict["remark"]?.string;//""
        self.status = dict["status"]?.int;//"0"
        self.time_add = dict["time_add"]?.string;//"2016/10/26 11:21:27"
        self.type = dict["type"]?.int;//"0"
        self.userid = dict["userid"]?.int;//"4020"
        }
    }
    
    
    //initToList( json:JSON(dict["huxing"] ) )  把JSON过的Any转为JSON
    //一定要是JSON要是 [Any] 的话 会装换失败，最后我还是选用这个JSON
    class func initToList(json: JSON)->[MyCollectsItemTo?]{
        if let items = json.array {
            var results = [MyCollectsItemTo?]()
            for item in items {
                let result = MyCollectsItemTo(jsons: item.dictionary )
                //                if(result != nil){//空还加个屁啊  json为“[]” 时 这是不会为空的。除非直接来了个nil
                //                    results.append(result!)
                //                }
                results.append(result)
            }
            return results;
        }
        return [MyCollectsItemTo?]()
    }
    
    //initToList( json:JSON(dict["huxing"] ) )  把JSON过的Any转为JSON
    //一定要是JSON要是 [Any] 的话 会装换失败，最后我还是选用这个JSON
    class func initToMap(json: JSON)->Dictionary<String,MyCollectsItemTo>{
        if let items = json.dictionary {
            var results = Dictionary<String,MyCollectsItemTo>()//取值的时候本身就是可选类型啊,所以这里不用跟数组一样弄可选类型
            for (key, value)  in items {
                let result = MyCollectsItemTo(jsons: value.dictionary )
                results[key] = result
            }
            return results;
        }
        return Dictionary<String,MyCollectsItemTo>()
    }
    
    
    
    
}

